"""后台定时任务 - 定期更新真题"""
import logging
from datetime import datetime, timedelta
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger
from apscheduler.triggers.cron import CronTrigger

from app.services.search.search_orchestrator import SearchOrchestrator
from app.services.search.storage_service import StorageService
from app.config import settings

logger = logging.getLogger(__name__)


class BackgroundTaskService:
    """后台任务服务"""
    
    def __init__(self):
        self.scheduler = BackgroundScheduler()
        self.search_orchestrator = SearchOrchestrator()
        self.storage_service = StorageService()
        self._is_running = False
    
    def start(self):
        """启动后台任务"""
        if self._is_running:
            logger.warning("后台任务已在运行")
            return
        
        # 每天凌晨2点执行一次搜索任务
        self.scheduler.add_job(
            self._daily_search_task,
            trigger=CronTrigger(hour=2, minute=0),
            id='daily_search',
            name='每日法考真题搜索',
            replace_existing=True
        )
        
        # 也可以按小时执行（用于测试）
        # self.scheduler.add_job(
        #     self._daily_search_task,
        #     trigger=IntervalTrigger(hours=settings.CRAWL_INTERVAL_HOURS),
        #     id='interval_search',
        #     name='定期法考真题搜索',
        #     replace_existing=True
        # )
        
        self.scheduler.start()
        self._is_running = True
        logger.info("后台任务已启动")
    
    def stop(self):
        """停止后台任务"""
        if not self._is_running:
            return
        
        self.scheduler.shutdown()
        self._is_running = False
        logger.info("后台任务已停止")
    
    def _daily_search_task(self):
        """每日搜索任务"""
        try:
            logger.info("开始执行每日搜索任务...")
            
            # 计算年份范围（最近5年）
            current_year = datetime.now().year
            years = list(range(current_year - 4, current_year + 1))
            
            # 所有科目
            subjects = ['民法', '刑法', '民诉', '刑诉', '行政', '商经', '三国']
            
            # 创建搜索记录
            year_range = f"{min(years)}-{max(years)}"
            search_record = self.storage_service.create_search_record(
                search_query=f"自动搜索 法考真题 {year_range}",
                search_type="both",
                year_range=year_range
            )
            
            # 执行搜索（同步执行，因为已经在后台线程中）
            import asyncio
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            
            result = loop.run_until_complete(
                self.search_orchestrator.search_and_save_questions(
                    years=years,
                    subjects=subjects,
                    search_record_id=search_record.id
                )
            )
            
            loop.close()
            
            logger.info(f"每日搜索任务完成: {result}")
            
        except Exception as e:
            logger.error(f"每日搜索任务失败: {str(e)}", exc_info=True)


# 全局后台任务服务实例
background_task_service = BackgroundTaskService()

